package com.dayaokeji.rhythmschoolstudent.client.message

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.dayaokeji.rhythmschoolstudent.R
import com.dayaokeji.rhythmschoolstudent.client.common.base.ActivityTemplateMethod
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity
import com.dayaokeji.rhythmschoolstudent.event.UpdateGroupEvent
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils
import com.dayaokeji.rhythmschoolstudent.wiget.CreateGroupDialog
import com.dayaokeji.rhythmschoolstudent.wiget.GroupInfo
import com.dayaokeji.server_api.ApiUtils
import com.dayaokeji.server_api.ServerResponse
import com.dayaokeji.server_api.api.GroupApi
import com.dayaokeji.server_api.domain.Member
import com.dayaokeji.server_api.domain.NewCreateGroup
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_groups.*
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import java.util.ArrayList

/**
 * 群组列表
 */
class GroupsActivity : BaseActivity() , ActivityTemplateMethod{

    private val groupApi by lazy { ApiUtils.getApi(GroupApi::class.java) }
    private var createCall: Call<ServerResponse<Int>>? = null

    companion object {
        private const val EXTRA_DETAIL_ID = "course_detail_id"
        private const val EXTRA_TYPE = "type"

        fun navigation(context: Context, courseDetailId: Int,type: Int) {
            val intent = Intent(context, GroupsActivity::class.java)
            intent.putExtra(EXTRA_DETAIL_ID,courseDetailId)
            intent.putExtra(EXTRA_TYPE,type)
            context.startActivity(intent)
        }
    }

    private var detailId: Int = -1
    private var type: Int = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_groups)
        toolbar?.let {
            setSupportActionBar(it)
        }
        init()
    }

    override fun init() {
        detailId = intent.getIntExtra(EXTRA_DETAIL_ID,-1)
        type = intent.getIntExtra(EXTRA_TYPE,-1)
        super.init()
    }

    override fun setupView() {
        if (detailId == -1) {
            Logger.d("course detail is -1")
            return
        }
    }

    override fun setupViewData() {
        supportFragmentManager.beginTransaction().replace(R.id.fl_content, ConversationsFragment.newInstance(false)).commit()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.groups,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        item?.let {
            when (it.itemId) {
                R.id.menu_create_group -> {
                    createGroup()
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun createGroup() {
        val dialogFragment = CreateGroupDialog.newInstance(detailId,type)
        dialogFragment.show(supportFragmentManager, "create_group")
        dialogFragment.setSubmitListener(object : CreateGroupDialog.SubmitListener {
            override fun click(groupInfo: GroupInfo) {
                if (UserUtils.getUserInfo() != null) {
                    val createGroup = NewCreateGroup()
                    createGroup.name = groupInfo.name
                    createGroup.remark = groupInfo.intro
                    createGroup.visibility = 2
                    createGroup.master = UserUtils.getUserInfo()!!.id
                    createGroup.members = getUserIds(groupInfo.member)
                    createCall = groupApi.newCreate(createGroup)
                    createCall?.enqueue(object : ServerCallback<Int>() {
                        override fun onResponse(success: Boolean, response: ServerResponse<Int>) {
                            if (success) {
                                ToastUtils.success(getString(R.string.create_success))
                                EventBus.getDefault().post(UpdateGroupEvent())
                            }
                        }
                    })
                }
            }
        })
    }

    private fun getUserIds(userInfos: List<Member>?): List<Int>? {
        val userIds = ArrayList<Int>()
        userIds.add(Integer.valueOf(UserUtils.getUserInfo()!!.id))
        if (userInfos != null) {
            for (userInfo in userInfos) {
                if (userInfo.userId != 0) {
                    userIds.add(Integer.valueOf(userInfo.userId))
                }
            }
            return userIds
        }
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        createCall?.cancel()
    }
}
